import React, { useEffect, useRef, useState } from 'react'
import { Table, Menu, Input, Button, message, Tag, Card, Modal } from 'antd';
import AddManagement from './AddManagement'
import AddadministerModel from './AddadministerModel'
import { getControllersList, GetManagementList, GetlockersList, Del_Management, Del_Batch } from './service'
import { Action, SearchForm, TableCard } from 'components';
import { FormOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';

const { confirm } = Modal
const ZoneManagement = () => {
  // 添加物理区
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 添加管理器
  const [AddModelOpen, setAddModelOpen] = useState(false)
  // 物理分区
  const [PhysicalArea, setPhysicalArea] = useState([])
  // 选中的管理区
  const [selectedKeys, setSelectedKeys] = useState([''])
  // 总数
  const [Total, setTotal] = useState(0);

  const [dataSource, setDataSource] = useState([]);

  const [isFetching, setIsFetching] = useState(false);
  // 查询参数
  const [SearchParams, setSearchParams] = useState({
    current: 1,
    pageSize: 10,
    locker_number: "",
    area_name: ""
  });
  // 侧边选择栏
  const [items, setitems] = useState([])



  useEffect(() => {
    GetPhysicalAreaData()
    GetManagement()
  }, [])


  const GetPhysicalAreaData = () => {

    getControllersList().then(res => {

      if (!res.data.list) return
      const str = res.data.list
        .map(item => {
          return { value: item.id, label: item.physical_zone + "区" }
        })

      setPhysicalArea(str);

    })
  }

  const GetManagement = () => {

    GetManagementList().then(res => {
     setitems([
        {
          key: '', label: <div onClick={(e) => e.stopPropagation()}>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setAddModelOpen(true)}>新增管理区</Button>
          </div>
        },

      ])
      if (!res.data) return

      let list = res.data.map((item) => {
        return {
          key: item.area_name,
          label: <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>{item.area_name}</div>
            <div style={{ fontSize: 12 }} onClick={() => Allocation(item)}><FormOutlined /></div>
          </div>
        }
      })
 
      setitems((pre) => [...pre, ...list]);

      setSelectedKeys([res.data[0].area_name])

      setSearchParams({ ...SearchParams, area_name: res.data[0].area_name })
      GetTableList({ area_name: res.data[0].area_name })
    })

  }


  const GetTableList = (params) => {

    setIsFetching(true)
    GetlockersList(params).then(res => {
      if (!res.data.list) return setIsFetching(false)
      setDataSource(res.data.list);

      setTotal(res.data.total)
      setIsFetching(false);
    });
  }


  const [Edit, EditMsg] = useState({})
  const Allocation = (item) => {
    console.log('分配', item)
    EditMsg(item)
    setAddModelOpen(true)
  }

  const handleClose = (tag) => {
    console.log(tag)
    confirm({
      title: `确定要删除${tag.label}吗`,
      content: '删除后无法恢复',
      onOk() {
        console.log('OK');
        Del_Management(tag.value).then((res) => {
          console.log(res)
          if (res.code == 0) {
            message.success("删除成功")
            GetPhysicalAreaData()
          } else {
            message.error("删除失败")
          }


        })

      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };


  const [selectionIds, setSelectionIds] = useState([]);
  const rowSelection = {
    onChange: (selectedRowKeys) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`);
      setSelectionIds(selectedRowKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };




  return (
    <>
      <Card title='物理分区' extra={<Button type='primary' icon={<PlusOutlined />} onClick={() => { setIsModalOpen(true) }}>添加物理区</Button>}>

        {
          PhysicalArea.map(item => <Tag color="green" onClose={(e) => {
            e.preventDefault();
            handleClose(item);
          }} closable key={item.value} style={{ margin: 6, fontSize: 14 }}>{item.label}</Tag>)
        }


      </Card>
      <br />
      <div style={{ display: 'flex', }}>
        <div style={{ width: 210 }}>
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            style={{ border: 'none', minHeight: "73vh" }}
            onSelect={({ selectedKeys }) => {
              console.log('selectedKeys: ', selectedKeys);
              setSelectedKeys(selectedKeys)
              GetTableList({ area_name: selectedKeys[0] })
              setSearchParams({ ...SearchParams, area_name: selectedKeys[0] })
            }}
            items={items}
          >
          </Menu>
        </div>
        <div style={{ maxheight: "calc(73vh)", width: 'calc(100vw - 210px)', marginLeft: 20 }}>
          <SearchForm>
            <SearchForm.Item span={8} title="柜号">
              <Input allowClear placeholder="请输入" onChange={(e) => {

                GetTableList({ ...SearchParams, locker_number: e.target.value })
                setSearchParams({ ...SearchParams, locker_number: e.target.value })
              }} />
            </SearchForm.Item>
          </SearchForm>

          <TableCard
            loading={isFetching}
            rowKey="id"
            dataSource={dataSource}
            onReload={GetTableList}
            // actions={[
            //   <>
            //     {/* <Button type="primary" icon={<PlusOutlined />} onClick={() => setFlag(false)}>批量新建</Button> */}
            //     <Button type="danger" disabled={!selectionIds.length} icon={<DeleteOutlined />} onClick={() => {
            //       confirm({
            //         title: "确定要删除吗？",
            //         content: `${selectionIds}`,
            //         okText: "删除",
            //         okType: 'danger',
            //         cancelText: "取消",
            //         onOk: () => {
            //           console.log(selectionIds)
                      
            //           let ids = selectionIds.map(item => item.toString())
            //           console.log(ids)

            //           Del_Batch({ ids }).then((res) => {
            //             if (res.code == 0) {
            //               message.success("删除成功");
            //               setSelectionIds([]);
            //               GetManagement()
            //             }

            //           })
            //         },
            //         onCancel: () => {

            //         },
            //       });
            //     }}>批量删除</Button>
            //   </>
            // ]}
            pagination={{
              showSizeChanger: true,
              showLessItems: true,
              showTotal: total => `共 ${Total} 条`,
              total: Total,
              current: SearchParams.page,
              pageSizeOptions: ['10', '20', '50', '100']
            }}

            // rowSelection={{
            //   type: "checkbox",
            //   ...rowSelection,
            // }}
          >
            <Table.Column title="区号" dataIndex="physical_zone" />
            <Table.Column title="区域" dataIndex="locker_user_type" />
            <Table.Column title="柜号" dataIndex="locker_number" />
            <Table.Column title="柜名" dataIndex="locker_name" render={info => (
              <div>{info == 1 ? "正常" : "异常"}</div>
            )} />
            {/* <Table.Column title="在线状态" dataIndex="is_online"
              render={info => {

                return info ? <Tag color="success">在线</Tag > : <Tag color="error">不在线</Tag >
              }} /> */}
            <Table.Column title="柜类型" dataIndex="locker_product_class" />
            <Table.Column title="柜品种" dataIndex="locker_type" />
            <Table.Column title="规格" dataIndex="locker_spec_name" />

          </TableCard>
        </div>
      </div>



      {
        isModalOpen && <AddManagement GetData={GetPhysicalAreaData} isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} />
      }

      {
        AddModelOpen && <AddadministerModel EditMsg={EditMsg} Edit={Edit} GetData={GetManagement} isModalOpen={AddModelOpen} setIsModalOpen={setAddModelOpen} />
      }

    </>
  )
}

export default ZoneManagement